package com.kang.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.InventoryLiquidation;
import com.kang.pojo.InventoryLiquidation_itemInformation;
import com.kang.pojo.ItemDetail;
import com.kang.pojo.ReturnRequest;
import com.kang.service.CategoryService;
import com.kang.service.InventoryLiquidationService;
import com.kang.service.WarehouseService;
import com.kang.until.GeneratingPDF;
import com.vonechina.entity.page.ItemLossPage;
import com.vonechina.entity.page.LiquidationListPage;
import com.vonechina.entity.page.LiquidationStatisticsListPage;

/**
 * 库存盘点控制层
 * @author wd
 *
 */
@Controller
@RequestMapping("inventoryLiquidation")
@SessionAttributes({ "liquidationListPage","liquidationStatisticsListPage"})
public class InventoryLiquidationController extends com.kang.controller.Controller {
	/**
	 * 库存盘点服务层接口
	 */
	@Resource
	private InventoryLiquidationService inventoryLiquidationService;
	/**
	 * 仓库服务层接口
	 */
	@Resource
	private WarehouseService warehouseService;
	/**
	 * 类别服务层接口
	 */
	@Resource
	private CategoryService cService;

	
	/**
	 * 查询盘点单
	 * @param session	会话
	 * @param model	Spring模型
	 * @param liquidationListPage	查询条件（封装的分页实体类）
	 * @return	前往查询库存盘点页面
	 */
	@RequestMapping("selectByWhere")
	public String selectByWhere(HttpSession session,Model model,LiquidationListPage liquidationListPage) {
		initRight(session);
		if (checkRight("查看库存盘点") != SUCCESS && checkRight("查看全部库存盘点") != SUCCESS) {
			return "basic/noRight";
		}
		if (checkRight("查看全部库存盘点") == SUCCESS) {
			liquidationListPage.setCreatePersonID(null);
		} else {
			liquidationListPage.setCreatePersonID(userID);
		}
		model.addAttribute("userID", userID);
		model.addAttribute("isAdd", checkRight("新增库存盘点") == SUCCESS);
		model.addAttribute("isEditAll", checkRight("编辑全部库存盘点") == SUCCESS);
		
		//得到总条数
		liquidationListPage.setRows(inventoryLiquidationService.selectByWhereCount(liquidationListPage));
		model.addAttribute("pandianList", inventoryLiquidationService.selectByWhereList(liquidationListPage));
		liquidationListPage.setPageUrl("inventoryLiquidation/selectByWhere.do");
		model.addAttribute("page", liquidationListPage);
		return "stock/inventoryLiquidation/listInventoryLiquidation";
	}
	
	/**
	 * 根据库存盘点id删除库存盘点
	 * @param session	会话
	 * @param request	请求
	 * @param inventoryID	盘点ID
	 * @param p_userid	创建盘点的用户ID
	 * @return	JSON字符串
	 */
	@RequestMapping("deleteInventoryLiquidationById")
	@ResponseBody
	public String deleteInventoryLiquidationById(HttpSession session, ReturnRequest request,int inventoryID,int p_userid){
		AjaxResult result = new AjaxResult();
		
		initRight(session);
		if (p_userid == userID && checkRight("新增库存盘点") == SUCCESS) {
		} else if (checkRight("编辑全部库存盘点") == SUCCESS) {
		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		
		if(inventoryLiquidationService.deleteInventoryLiquidationById(inventoryID)){
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 根据盘点id查询盘点详情
	 * @param session	会话
	 * @param model	Spring模型
	 * @param inventoryID	盘点ID
	 * @return	查询信息后前往编辑盘点页面
	 */
	@RequestMapping("toEdit")
	public String toEdit(HttpSession session,Model model,Integer inventoryID) {
		InventoryLiquidation pandian = inventoryLiquidationService.getInventoryLiquidationById(inventoryID);
		initRight(session);
		if (pandian.getCreatePersonID() == userID && checkRight("新增库存盘点") == SUCCESS) {
			model.addAttribute("isEdit", true);
		} else if (checkRight("编辑全部库存盘点") == SUCCESS) {
			model.addAttribute("isEdit", true);
		} else {
			model.addAttribute("isEdit", false);
		}
		
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());//所有仓库
		model.addAttribute("categoryList", cService.listAllCategory());//所有类别
		model.addAttribute("itemList", inventoryLiquidationService.listItemByInventoryID(inventoryID));//盘点的物品列表
		model.addAttribute("pandian",pandian);//盘点信息
		return "stock/inventoryLiquidation/editInventoryLiquidation";
	}
	
	/**
	 * 添加盘点物品时根据仓库等信息查询物品列表
	 * @param page	查询条件
	 * @return	集合List的JSON字符串
	 */
	@RequestMapping("listNotAddItem")
	@ResponseBody
	public String listNotAddItem(ItemLossPage page) {
		AjaxResult result = new AjaxResult();
		List<ItemDetail> list = inventoryLiquidationService.listItemDetailForLoss(page);
		result.setTotal(page.getRows());
		result.setRows(list);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 执行编辑保存盘点物品及盘点单信息
	 * @param session	会话
	 * @param inventoryLiquidation	库存盘点信息（实体类）
	 * @param itemIds	批次ID数组集合
	 * @param number	物品盘点前数量数组集合
	 * @param itemInformationIDs	物品ID数组集合
	 * @param recordNumberS	实际盘点数量数组集合
	 * @return	JSON字符串
	 */
	@RequestMapping("executiveEditLiquidationInfo")
	@ResponseBody
	public String executiveEditLiquidationInfo(HttpSession session, InventoryLiquidation inventoryLiquidation, Integer[] itemIds,
			Integer[] number, Integer[] itemInformationIDs, Integer[] recordNumberS) {
		AjaxResult result = new AjaxResult();
		
		initRight(session);
		if (inventoryLiquidation.getCreatePersonID() == userID && checkRight("新增库存盘点") == SUCCESS) {
		} else if (checkRight("编辑全部库存盘点") == SUCCESS) {
		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		
		inventoryLiquidation.setLastModifiedID((Integer) session.getAttribute("userID"));//最后修改人id
		int a = inventoryLiquidationService.updateInventoryLiquidation(inventoryLiquidation);
		if (a > 0) {
			inventoryLiquidationService.deleteItemNotInLiquidationSingle(inventoryLiquidation.getInventoryID(), itemIds);
			inventoryLiquidationService.saveLiquidationItemList(inventoryLiquidation.getInventoryID(), itemIds, 
					number,itemInformationIDs,recordNumberS,inventoryLiquidation.getWarehouseID());
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 保存信息并提交盘点单
	 * @param session	会话
	 * @param inventoryLiquidation	库存盘点（实体类）
	 * @param itemIds	批次ID数组集合
	 * @param number	物品盘点前数量数组集合
	 * @param itemInformationIDs	物品ID数组集合
	 * @param recordNumberS	实际盘点数量数组集合
	 * @return	JSON字符串
	 */
	@RequestMapping("saveAndSubmitLiquidationInfo")
	@ResponseBody
	public String saveAndSubmitLiquidationInfo(HttpSession session, InventoryLiquidation inventoryLiquidation, Integer[] itemIds,
			Integer[] number, Integer[] itemInformationIDs, Integer[] recordNumberS) {
		AjaxResult result = new AjaxResult();
		
		initRight(session);
		if (inventoryLiquidation.getCreatePersonID() == userID && checkRight("新增库存盘点") == SUCCESS) {
		} else if (checkRight("编辑全部库存盘点") == SUCCESS) {
		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		
		inventoryLiquidation.setLastModifiedID((Integer) session.getAttribute("userID"));//最后修改人id
		int a = inventoryLiquidationService.updateInventoryLiquidation(inventoryLiquidation);
		if (a > 0) {
			inventoryLiquidationService.saveAndSubmitinventoryLiquidation((Integer) session.getAttribute("userID"),inventoryLiquidation.getInventoryID());//提交盘点单
			inventoryLiquidationService.deleteItemNotInLiquidationSingle(inventoryLiquidation.getInventoryID(), itemIds);
			inventoryLiquidationService.saveLiquidationItemList(inventoryLiquidation.getInventoryID(), itemIds, 
					number,itemInformationIDs,recordNumberS,inventoryLiquidation.getWarehouseID());
			inventoryLiquidationService.submitUpdateLiquidationAfterNumberForStock(itemIds,number);//盘点提交后修改实际库存数量
			
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 查询仓库类别信息，去到添加盘点界面
	 * @param session	会话
	 * @param model	Spring模型
	 * @return	前往添加盘点界面
	 */
	@RequestMapping("toAddInventoryLiquidation")
	public String toAddInventoryLiquidation(HttpSession session,Model model) {
		
		initRight(session);
		if (checkRight("新增库存盘点") != SUCCESS) {
			return "basic/noRight";
		}
		
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());//所有仓库
		model.addAttribute("categoryList", cService.listAllCategory());//所有类别
		model.addAttribute("userName", session.getAttribute("userName"));//当前操作人
		return "stock/inventoryLiquidation/addInventoryLiquidation";
	}
	
	/**
	 * 保存新增的盘点单及所盘点的物品
	 * @param session	会话
	 * @param inventoryLiquidation	库存盘点信息（实体类）
	 * @param itemIds	批次ID数组集合
	 * @param number	物品盘点前数量数组集合
	 * @param itemInformationIDs	物品ID数组集合
	 * @param recordNumberS	实际盘点数量数组集合
	 * @return	JSON字符串（成功或失败）
	 */
	@RequestMapping("saveNewAddLiquidationInfo")
	@ResponseBody
	public String saveNewAddLiquidationInfo(HttpSession session, InventoryLiquidation inventoryLiquidation, Integer[] itemIds,
			Integer[] number, Integer[] itemInformationIDs, Integer[] recordNumberS) {
		AjaxResult result = new AjaxResult();
		
		if (checkRight("新增库存盘点") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		
		inventoryLiquidation.setInventoryNumber(inventoryLiquidationService.selectMaxLiquidationNumber());//生成盘点单号
		inventoryLiquidation.setCreatePersonID((Integer) session.getAttribute("userID"));//创建人id
		inventoryLiquidation.setLastModifiedID((Integer) session.getAttribute("userID"));//最后修改人id
		
		int a = inventoryLiquidationService.addNewInventoryLiquidation(inventoryLiquidation);//新增盘点
		//根据盘点单号查询盘点id
		Integer inventorylossid = inventoryLiquidationService.getIdByInventoryNumber(inventoryLiquidation.getInventoryNumber());
		if (a > 0) {
			inventoryLiquidationService.deleteItemNotInLiquidationSingle(inventorylossid, itemIds);
			inventoryLiquidationService.saveLiquidationItemList(inventorylossid, itemIds, 
					number,itemInformationIDs,recordNumberS,inventoryLiquidation.getWarehouseID());
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 保存并提交新增的盘点单及所盘点的物品
	 * @param session	会话
	 * @param inventoryLiquidation	库存盘点信息（实体类）
	 * @param itemIds	批次ID数组集合
	 * @param number	物品盘点前数量数组集合
	 * @param itemInformationIDs	物品ID数组集合
	 * @param recordNumberS	实际盘点数量数组集合
	 * @return	JSON字符串（成功或失败）
	 */
	@RequestMapping("saveAndSubmitNewAddInventoryLiquidation")
	@ResponseBody
	public String saveAndSubmitNewAddInventoryLiquidation(HttpSession session, InventoryLiquidation inventoryLiquidation, Integer[] itemIds,
			Integer[] number, Integer[] itemInformationIDs, Integer[] recordNumberS) {
		AjaxResult result = new AjaxResult();
		
		if (checkRight("新增库存盘点") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		
		inventoryLiquidation.setInventoryNumber(inventoryLiquidationService.selectMaxLiquidationNumber());//生成盘点单号
		inventoryLiquidation.setCreatePersonID((Integer) session.getAttribute("userID"));//创建人id
		inventoryLiquidation.setLastModifiedID((Integer) session.getAttribute("userID"));//最后修改人id
		
		int a = inventoryLiquidationService.addNewInventoryLiquidation(inventoryLiquidation);//新增盘点
		//根据盘点单号查询盘点id
		Integer inventorylossid = inventoryLiquidationService.getIdByInventoryNumber(inventoryLiquidation.getInventoryNumber());
		if (a > 0) {
			inventoryLiquidationService.saveAndSubmitinventoryLiquidation((Integer) session.getAttribute("userID"),inventorylossid);//提交盘点单
			inventoryLiquidationService.deleteItemNotInLiquidationSingle(inventorylossid, itemIds);
			inventoryLiquidationService.saveLiquidationItemList(inventorylossid, itemIds, 
					number,itemInformationIDs,recordNumberS,inventoryLiquidation.getWarehouseID());
			inventoryLiquidationService.submitUpdateLiquidationAfterNumberForStock(itemIds,number);//盘点提交后修改实际库存数量
			
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 库存盘点统计报表
	 * @param session	会话
	 * @param model	Spring
	 * @param liquidationStatisticsListPage	查询条件（封装的分页实体类）
	 * @return
	 */
	@RequestMapping("selectInventoryLiquidationStatisticsList")
	public String selectInventoryLiquidationStatisticsList(HttpSession session,Model model,LiquidationStatisticsListPage liquidationStatisticsListPage) {
		initRight(session);
		if (checkRight("盘点统计") != SUCCESS) {
			return "basic/noRight";
		}
		
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());//所有仓库
		model.addAttribute("categoryList", cService.listAllCategory());//所有类别
		model.addAttribute("liquidationStatisticsList", inventoryLiquidationService.selectInventoryLiquidationStatisticsList(liquidationStatisticsListPage));//统计表

		liquidationStatisticsListPage.setPageUrl("inventoryLiquidation/selectInventoryLiquidationStatisticsList.do");
		model.addAttribute("page", liquidationStatisticsListPage);
		return "systemStatistics/inventoryLiquidationStatistics/inventoryLiquidationStatistics";
	}
	
	/**
	 * 打印盘点单
	 * @param session	会话
	 * @param response	请求
	 * @param inventoryID	盘点ID
	 * @throws Exception	
	 */
	@RequestMapping("printInventoryLiquidation")
	public void printInventoryLiquidation(HttpSession session,HttpServletResponse response,Integer inventoryID) throws Exception{
		InventoryLiquidation pandian = inventoryLiquidationService.getInventoryLiquidationById(inventoryID);
		List<InventoryLiquidation_itemInformation> itemList = inventoryLiquidationService.listItemByInventoryID(inventoryID);//盘点的物品列表
		
		//此方法为直接下载文件
		File file = GeneratingPDF.generateInventoryLiquidationPDF(pandian, itemList);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    fis.close();
				    response.reset();
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
	}
}
